package fileExercise;

import java.io.*;
import java.time.LocalDate;
import java.util.Objects;
import java.util.UUID;

/**
 * @classname:FileUtil
 * @description:
 * @author: Mr.Z
 * @date: 2020/12/17 19:59
 * @version: 0.1
 * @since:1.8
 */
public class FileUtil {

    public static void main(String[] args) {
        fileUpload("C:\\Users\\JAVASM\\Desktop\\Snipaste_2020-12-15_15-47-14.png");
    }

    private static final String TAGET_UPLOAD_PATH = "day16/upload/user/";

    public static void fileUpload(String sourceFile) {
        Objects.requireNonNull(sourceFile);
        //处理删除图片路径
        //处理图片的图片名和为了防止文件冲突添加uuid来区分图片名字，拼接-号来以后为了给用户显示提供方便
        String targetFileName = UUID.randomUUID().toString().replaceAll("-", "") + "-" + sourceFile.substring(sourceFile.lastIndexOf(File.separator) + 1);
        //以当前日期创建文件夹
        File parentDir = new File(TAGET_UPLOAD_PATH,LocalDate.now().toString());
        //判断当前父级目录是否存在，不存在创建
        if (!parentDir.exists()) {
            parentDir.mkdirs();
        }

        try (
                BufferedInputStream in = new BufferedInputStream(new FileInputStream(sourceFile));
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(parentDir, targetFileName)));
        ) {
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = in.read(bytes)) != -1) {
                out.write(bytes, 0, len);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
